package dao

import javax.inject.Inject
import models.Tables._
import play.api.db.slick.{DatabaseConfigProvider, HasDatabaseConfigProvider}
import slick.jdbc.JdbcProfile

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future


/**
 * Created by yz on 2018/7/17
 */
class SignInDao @Inject()(protected val dbConfigProvider: DatabaseConfigProvider) extends
  HasDatabaseConfigProvider[JdbcProfile] {

  import utils.MyPostgresProfile.api._

  type MyRow = SignInRow
  val table = SignIn

  def selectOp(userId: Int) = db.run(table.filter(_.userId === userId).result.
    headOption)

  def select(userId: Int) = db.run(table.filter(_.userId === userId).result.
    head)

  def update(row: MyRow) = db.run(table.filter(_.userId === row.userId).update(row)).
    map(_ => ())

  def insert(row: MyRow)= db.run(table += row).map(_ => ())

  def insertOrUpdate(row: MyRow) = {
    val action = {
      val userId = row.userId
      val delete = table.filter(_.userId===userId).delete
      val insert = table += row
      delete.flatMap(_ => insert)
    }.transactionally
    db.run(action).map(_ => ())
  }

}
